from django.contrib import auth
from django.http.response import HttpResponseRedirect
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.shortcuts import render

from rest_framework.authtoken.models import Token
from rest_framework.decorators import api_view
from rest_framework.response import Response


def testapi(request):
    # token = Token.objects.create(user=usr)
    # print(token.key)
    # return Response(token.key)
    pass


@api_view(['GET', 'POST'])
def web_auth(request):
    if request.method == 'GET':
        try:
            username = request.GET['username']
            password = request.GET['password']
        except:
            username = None
            password = None
        content = {}

        usr = auth.authenticate(username=username, password=password)
        print(usr)
        if usr is not None:
            auth.login(request, usr)

        else:
            form = AuthenticationForm()
            content['form'] = form

        # print(dir(form))

        # return HttpResponseRedirect("/eval/index", content)
        return render(request, 'register.html', content)

    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
        else:
            print('error')
        return HttpResponseRedirect("/eval/index")



